import { createContext, useState, useEffect, ReactNode } from 'react'
import { User, AuthContextType } from '../hooks/useAuth'

export const AuthContext = createContext<AuthContextType | undefined>(undefined)

interface AuthProviderProps {
    children: ReactNode
}



export function AuthProvider({ children }: AuthProviderProps) {
    const [isAuthenticated, setIsAuthenticated] = useState(false)
    const [user, setUser] = useState<User | null>(null)
  
    useEffect(() => {
      const token = localStorage.getItem('token')
      if (token) {
        checkAuth(token)
      }
    }, [])
  
    const checkAuth = async (token: string) => {
      try {
        const response = await fetch('/api/auth/me', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        if (response.ok) {
          const userData = await response.json()
          setUser(userData)
          setIsAuthenticated(true)
        } else {
          localStorage.removeItem('token')
          setIsAuthenticated(false)
          setUser(null)
        }
      } catch (error) {
        console.error('Auth check failed:', error)
        localStorage.removeItem('token')
      }
    }
  
    const login = async (email: string, password: string) => {
      try {
        const response = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password }),
        })
        
        if (!response.ok) {
          const data = await response.json()
          throw new Error(data.error || 'Login failed')
        }
        
        const data = await response.json()
        localStorage.setItem('token', data.token)
        setIsAuthenticated(true)
        setUser(data.user)
      } catch (error) {
        console.error('Login failed:', error)
        throw error
      }
    }
  
    const register = async (
      email: string,
      password: string,
      name: string,
      verifyCode: string
    ) => {
      try {
        const response = await fetch('/api/auth/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password, name, verifyCode }),
        })
        
        if (!response.ok) {
          const data = await response.json()
          throw new Error(data.error || 'Registration failed')
        }
        
        const data = await response.json()
        localStorage.setItem('token', data.token)
        setIsAuthenticated(true)
        setUser(data.user)
      } catch (error) {
        console.error('Registration failed:', error)
        throw error
      }
    }
  
    const resetPassword = async (email: string) => {
      try {
        const response = await fetch('/api/auth/reset-password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        })
        if (!response.ok) {
          throw new Error('Password reset request failed')
        }
      } catch (error) {
        console.error('Password reset failed:', error)
        throw error
      }
    }
  
    const logout = async () => {
      try {
        const token = localStorage.getItem('token')
        if (token) {
          await fetch('/api/auth/logout', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
        }
      } catch (error) {
        console.error('Logout failed:', error)
      } finally {
        localStorage.removeItem('token')
        setIsAuthenticated(false)
        setUser(null)
      }
    }
  
    return (
      <AuthContext.Provider 
        value={{ 
          isAuthenticated, 
          user, 
          login, 
          logout,
          register,
          resetPassword
        }}
      >
        {children}
      </AuthContext.Provider>
    )
  }